package com.se.nju.rtvps.network;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.text.MessageFormat;
import java.util.Enumeration;

import net.jxta.discovery.DiscoveryEvent;
import net.jxta.discovery.DiscoveryListener;
import net.jxta.discovery.DiscoveryService;
import net.jxta.document.Advertisement;
import net.jxta.endpoint.Message;
import net.jxta.id.IDFactory;
import net.jxta.impl.protocol.ModuleSpecAdv;
import net.jxta.peer.PeerID;
import net.jxta.peergroup.PeerGroup;
import net.jxta.pipe.PipeMsgEvent;
import net.jxta.pipe.PipeMsgListener;
import net.jxta.platform.NetworkManager;
import net.jxta.protocol.PipeAdvertisement;
import net.jxta.util.JxtaBiDiPipe;

import com.se.nju.rtvps.main.ServiceConstants;

public class RTVPSClient implements DiscoveryListener, PipeMsgListener {
	private NetworkManager manager;
	private PeerGroup npg;
	
	public RTVPSClient()throws Exception{
		manager = new NetworkManager(NetworkManager.ConfigMode.EDGE, "RTVPSClient", new File(new File(".cache"), "RTVPSClient").toURI());
	}
	
	public void start()throws Exception{
		manager.getConfigurator().addSeedRendezvous(new URI("http://192.168.34.39:9700"));
		npg = manager.startNetwork();
        boolean connected = manager.waitForRendezvousConnection(5000);
        System.out.println(MessageFormat.format("Connected :{0}", connected));
		DiscoveryService ds = npg.getDiscoveryService();
		ds.addDiscoveryListener(this);
		ds.getRemoteAdvertisements(
				null, DiscoveryService.ADV, "Name", 
				ServiceConstants.SERVERSIDE_CONTROL_SERVICE_SPECNAME, 1);
		while(true){
			Thread.sleep(2000);
		}
	}

	public void discoveryEvent(DiscoveryEvent event) {
		System.out.println("found!!");
        Enumeration<Advertisement> res = event.getSearchResults();

        if (res != null) {

               while (res.hasMoreElements()) {

            	  // System.out.println(res.nextElement());
                   processAdv( res.nextElement());

               }

        }
	}

	private void processAdv(Advertisement advertisement){
		try {
			PipeAdvertisement pipeAdv = ((ModuleSpecAdv)advertisement).getPipeAdvertisement();
			JxtaBiDiPipe bdPipe = new JxtaBiDiPipe(npg, pipeAdv, 5000, this, true);
			Message msg = new Message();
			bdPipe.sendMessage(msg);
		} catch (IOException e) {
			System.out.println("Client Connect to ServerControlService Error!!\n"+e.getMessage());
			e.printStackTrace();
		}
	}

	public void pipeMsgEvent(PipeMsgEvent event) {
		System.out.println("Msg received!~~~~~~~~~~~~~~~~~~\n"+event.getMessage()+"\n\n");
	}
	public static void main(String[] args){
		RTVPSClient client;
		try {
			client = new RTVPSClient();
			client.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
